/**
 * Project Name:HomeActivity
 * Date:2016-4-7下午7:06:23
 * Copyright (c) 2016, askzhao All Rights Reserved.
 *
 */
package com.kkd.kkdapp.view;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.kkd.kkdapp.BaseApplication;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.adapter.ShareGridViewAdapter;
import com.kkd.kkdapp.adapter.ShareGridViewAdapter.OnItemCliclistener;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.Share;
import com.kkd.kkdapp.utils.share.AccessTokenKeeper;
import com.kkd.kkdapp.utils.share.SinaConstants;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;

/**
 * ClassName: ShareView <br/>
 * date: 2016-4-7 下午7:06:23 <br/>
 * 
 * @author askzhao
 * @version
 */
public class ShareView extends RelativeLayout {

	private Context mContext;
	private List<Share> mList;

	public ShareView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		mContext = context;
		initUI();
	}

	public ShareView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		initUI();
	}

	public ShareView(Context context) {
		super(context);
		mContext = context;
		initUI();
	}

	private void initUI() {
		View view = RelativeLayout.inflate(mContext,
				R.layout.global_share_dialog, null);
		addView(view);
		GridView first_line_view = (GridView) view
				.findViewById(R.id.first_line_view);
		mList = new ArrayList<Share>();
		Share share;
		// 微信
		if (IsHasWeixin()) {
			share = new Share();
			share.setShareImg(R.drawable.share_btn_wechat);
			share.setShareName("微信");
			mList.add(share);
		}
		// 微信朋友圈
		if (IsHasWeixin()) {
			share = new Share();
			share.setShareImg(R.drawable.share_btn_wechat_circle);
			share.setShareName("微信朋友圈");
			mList.add(share);
		}
		// 新浪微博
//		if(!IsHasSina()){
			share = new Share();
			share.setShareImg(R.drawable.share_btn_sina);
			share.setShareName("微博");
			mList.add(share);
//		}
		
		// QQ
		if (IsHasQQ()) {
			share = new Share();
			share.setShareImg(R.drawable.share_btn_qq);
			share.setShareName("QQ");
			mList.add(share);
		}
		// QQ空间
		if (IsHasQQ()) {
			share = new Share();
			share.setShareImg(R.drawable.share_btn_qq);
			share.setShareName("QQ空间");
			mList.add(share);
		}

		ShareGridViewAdapter adapter = new ShareGridViewAdapter(mContext, mList);
		first_line_view.setAdapter(adapter);
		adapter.setonItemClickListener(new OnItemCliclistener() {

			@Override
			public void onPosition(int id) {
				if (mList.get(id).getShareName().equals("QQ空间")) {
					mShareCallback.onShareToQzone();
				}
				if (mList.get(id).getShareName().equals("QQ")) {
					mShareCallback.onShareToQQ();
				}
				if (mList.get(id).getShareName().equals("微博")) {			
					
					mShareCallback.onShareToSina();
				}
				if (mList.get(id).getShareName().equals("微信朋友圈")) {
					mShareCallback.onShareToWxCycle();
				}
				if (mList.get(id).getShareName().equals("微信")) {
					mShareCallback.onShareToWx();
				}
//				switch (id) {
//				case 0: // 有微信分享第一个是微信分享，没有微信分享第一个是新浪分享
//					if (IsHasWeixin()) {
//						mShareCallback.onShareToWx();
//					} else {
//						mShareCallback.onShareToSina();
//					}
//					break;
//				case 1: // 有微信分享第二个是微信朋友圈分享，没有微信分享第二个：有QQ则是QQ分享，没有则是空
//					if (IsHasWeixin()) {
//						mShareCallback.onShareToWxCycle();
//					} else {
//						if (IsHasQQ()) {
//							mShareCallback.onShareToQQ();
//						}
//					}
//					break;
//				case 2: // 有微信分享第三个是新浪微博，没有微信分享第三个：有QQ则是QQ空间分享，没有则是空
//					if (IsHasWeixin()) {
//						mShareCallback.onShareToSina();
//					} else {
//						if (IsHasQQ()) {
//							mShareCallback.onShareToQzone();
//						}
//					}
//					break;
//				case 3: // QQ
//					mShareCallback.onShareToQQ();
//					break;
//				case 4: // QQ 空间
//					mShareCallback.onShareToQzone();
//					break;
//				}
//
//				if (id == 0) {
//
//				} else if (id == 1) {
//
//				} else if (id == 2) {
//					if (IsHasWeixin()) {
//
//					}
//				}
			}
		});
//		ImageView wechat = (ImageView) view.findViewById(R.id.wechat);
//		wechat.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				if (IsHasWeixin()) {
//					// share2Friends(mContext, mShareContent.path);
//					mShareCallback.onShareToWx();
//				} else {
//					Toast.makeText(mContext, "请先安装微信客户端，再分享",
//							Toast.LENGTH_SHORT).show();
//				}
//			}
//
//		});
//		ImageView wechat_circle = (ImageView) view
//				.findViewById(R.id.wechat_circle);
//		wechat_circle.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				if (IsHasWeixin()) {
//					mShareCallback.onShareToWxCycle();
//					// share2wechat_circle(mContext, mShareContent.path);
//				} else {
//					Toast.makeText(mContext, "请先安装微信客户端，再分享",
//							Toast.LENGTH_SHORT).show();
//				}
//			}
//		});
//		ImageView sina = (ImageView) view.findViewById(R.id.sina);
//		sina.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				mShareCallback.onShareToSina();
//				// shareWeiBo(mContext, mShareContent.path);
//				// mAlertDialog.dismiss();
//			}
//		});
//		ImageView qq = (ImageView) view.findViewById(R.id.qq);
//		qq.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				if (IsHasQQ()) {
//					mShareCallback.onShareToQQ();
//					// share2QQ(mContext, mShareContent.path);
//				} else {
//					Toast.makeText(mContext, "请先安装QQ客户端，再分享",
//							Toast.LENGTH_SHORT).show();
//				}
//			}
//		});
//		ImageView qq_zone = (ImageView) view.findViewById(R.id.qq_zone);
//		qq_zone.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				if (IsHasQQ()) {
//					mShareCallback.onShareToQzone();
//					// share2QQZone(mContext, mShareContent.path,
//					// mShareContent.tagetUrl);
//				} else {
//					Toast.makeText(mContext, "请先安装QQ客户端，再分享",
//							Toast.LENGTH_SHORT).show();
//				}
//				// mAlertDialog.dismiss();
//			}
//		});

	}

	public boolean IsHasWeixin() {
		boolean mIsHasWeixin = false;
		// 通过查询，获得所有ResolveInfo对象.
		PackageManager pm = mContext.getPackageManager();
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		List<ResolveInfo> resolveInfos = pm
				.queryIntentActivities(mainIntent, 0);
		for (ResolveInfo i : resolveInfos) {
			if (i.activityInfo.packageName.contains("com.tencent.mm")) {
				mIsHasWeixin = true;
			}
		}
		return mIsHasWeixin;
	}

	public boolean IsHasQQ() {
		boolean mIsHasQQ = false;
		// 通过查询，获得所有ResolveInfo对象.
		PackageManager pm = mContext.getPackageManager();
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		List<ResolveInfo> resolveInfos = pm
				.queryIntentActivities(mainIntent, 0);
		for (ResolveInfo i : resolveInfos) {
			if (i.activityInfo.packageName.contains("com.tencent.mobileqq")) {
				mIsHasQQ = true;
			}
		}
		return mIsHasQQ;
	}
	
	public boolean IsHasSina() {
		boolean mIsHasQQ = false;
		// 通过查询，获得所有ResolveInfo对象.
//		PackageManager pm = mContext.getPackageManager();
//		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
//		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
//		List<ResolveInfo> resolveInfos = pm
//				.queryIntentActivities(mainIntent, 0);
//		for (ResolveInfo i : resolveInfos) {
//			if (i.activityInfo.packageName.contains("com.sina.weibo")) {
//				mIsHasQQ = true;
//			}
//		}
		mIsHasQQ =((BaseActivity)mContext).mWeiboShareAPI.isWeiboAppInstalled();
		return mIsHasQQ;
	}

	ShareCallback mShareCallback = new ShareCallback() {

		@Override
		public void onShareToWxCycle() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onShareToWx() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onShareToSina() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onShareToQzone() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onShareToQQ() {
			// TODO Auto-generated method stub

		}
	};

	public void setShareCallback(ShareCallback nShareCallback) {
		mShareCallback = nShareCallback;
	}

	public interface ShareCallback {
		public void onShareToQQ();

		public void onShareToQzone();

		public void onShareToWx();

		public void onShareToWxCycle();

		public void onShareToSina();
	}
	
	
	
	/** 封装了 "access_token"，"expires_in"，"refresh_token"，并提供了他们的管理功能  */
    private Oauth2AccessToken mAccessToken;

	/**
     * 微博认证授权回调类。
     * 1. SSO 授权时，需要在 {@link #onActivityResult} 中调用 {@link SsoHandler#authorizeCallBack} 后，
     *    该回调才会被执行。
     * 2. 非 SSO 授权时，当授权结束后，该回调就会被执行。
     * 当授权成功后，请保存该 access_token、expires_in、uid 等信息到 SharedPreferences 中。
     */
    class AuthListener implements WeiboAuthListener {
        
        @Override
        public void onComplete(Bundle values) {
            // 从 Bundle 中解析 Token
            mAccessToken = Oauth2AccessToken.parseAccessToken(values);
            //从这里获取用户输入的 电话号码信息 
            String  phoneNum =  mAccessToken.getPhoneNum();
            if (mAccessToken.isSessionValid()) {
                // 显示 Token
//                updateTokenView(false);
//                
                // 保存 Token 到 SharedPreferences
                AccessTokenKeeper.writeAccessToken(mContext, mAccessToken);
                mShareCallback.onShareToSina();
            } else {
                // 以下几种情况，您会收到 Code：
                // 1. 当您未在平台上注册的应用程序的包名与签名时；
                // 2. 当您注册的应用程序包名与签名不正确时；
                // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                String code = values.getString("code");
                String message = "微博授权失败";
                if (!TextUtils.isEmpty(code)) {
                    message = message + "\nObtained the code: " + code;
                }
                Toast.makeText(mContext, message, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onCancel() {
            Toast.makeText(mContext, "取消微博授权", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(mContext, 
                    "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
}
